package com.dong.cutesms.activitys;

import java.util.ArrayList;

import com.dong.cutesms.R;
import com.dong.cutesms.components.CustomMenu;
import com.dong.cutesms.components.CustomMenu.OnMenuItemSelectedListener;
import com.dong.cutesms.components.CustomMenuItem;
import com.dong.cutesms.components.DialogActionSMS;
import com.dong.cutesms.components.DialogActionThread;
import com.dong.cutesms.components.DialogChooseAvatar;
import com.dong.cutesms.components.DialogWait1Time;
import com.dong.cutesms.constant.AppConstant;
import com.dong.cutesms.constant.AppParameters;
import com.dong.cutesms.models.Config;
import com.dong.cutesms.models.PeopleModel;
import com.dong.cutesms.models.UserModel;
import com.dong.cutesms.utils.SmsUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnMenuItemSelectedListener{
	private ListView listview;
	private SmsUtils smsUtils;
	public static ThreadSMSAdapter adapter;
	private Context context = this;
	private final int INSERT_CONTACT = 100;
	private final int VIEW_CONTACT = 200;
	private int contactID;
	
	private CustomMenu mMenu;
	public static final int MENU_ITEM_1 = 1;
	public static final int MENU_ITEM_2 = 2;
	public static final int MENU_ITEM_3 = 3;
	public static final int MENU_ITEM_4 = 4;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		smsUtils = new SmsUtils(getContentResolver(),getApplicationContext());
		//smsUtils.showTable();
		
		new LoadViewTask().execute();
		
	}
	private void configApplication(){
		smsUtils.importSms();
		Config config = new Config("status_access", "1");
		smsUtils.addConfig(config);
		//get user info
		int userAvatarID = smsUtils.getUserAvatar();
		UserModel user = new UserModel(userAvatarID);
		AppParameters.user = user;
	}
	
	private void setupComponents(){
		listview = (ListView) findViewById(R.id.lv_activity_main);
	}
	
	private void loadView(){
		AppParameters.listPeople = smsUtils.getPeopleList();
		adapter = new ThreadSMSAdapter(this);
		listview.setAdapter(adapter);
		if(listview == null){
			System.out.println("list view null");
		}
		setupMenu();
	}
	
	public void setupMenu(){
		mMenu = new CustomMenu(this, this, getLayoutInflater());
        mMenu.setHideOnSelect(true);
        mMenu.setItemsPerLineInPortraitOrientation(4);
        mMenu.setItemsPerLineInLandscapeOrientation(8);
        
        //load the menu items
        loadMenuItems();
	}
	
	public class ThreadSMSAdapter extends BaseAdapter {
		LayoutInflater inflater;
		ViewHolder viewHolder;
		boolean longpress = false;
		public ThreadSMSAdapter(Context context) {
			// TODO Auto-generated constructor stub
			inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return AppParameters.listPeople.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}
		
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			System.out.println("position:" + String.valueOf(position));
			if (convertView == null) {

				convertView = inflater.inflate(R.layout.item_activity_main, null);
				viewHolder = new ViewHolder();

				viewHolder.tv = (TextView) convertView
						.findViewById(R.id.tv_activity_main_displayname);
				viewHolder.recentMes = (TextView) convertView
						.findViewById(R.id.tv_activity_main_recentMes);
				
				viewHolder.icon = (ImageView) convertView.findViewById(R.id.btn_activity_main_icon);
				viewHolder.status = (ImageView) convertView.findViewById(R.id.status_message);
				convertView.setTag(viewHolder);

			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			final PeopleModel people = AppParameters.listPeople.get(position);
			
			viewHolder.tv.setText(people.displayName);
			viewHolder.recentMes.setText(getRecentMessage(people.recentMessage));
			
			if(people.hasSms>0){
				viewHolder.status.setVisibility(View.VISIBLE);
			}
			else{
				viewHolder.status.setVisibility(View.INVISIBLE);
			}
			
			final int temp = position;
			viewHolder.icon.setImageResource(people.avatarID);
			viewHolder.icon.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View paramView) {
					System.out.println(temp);
					//Dialog dialog = new DialogChooseAvatar(getApplicationContext()).getInstance();
					AppParameters.people = people;
					Dialog dialog = new DialogChooseAvatar(context).getInstance();
					
				}
			});
			
			convertView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View paramView) {
					if(!longpress){
						System.out.println(temp);
						AppParameters.people = AppParameters.listPeople.get(temp);
						AppParameters.peoplePosition = temp;
						Intent intent = new Intent(MainActivity.this,ShowMainSmsActivity_2.class);
						startActivity(intent);
					}
					longpress = false;
				}
			});
			
			convertView.setOnLongClickListener(new OnLongClickListener() {
				@Override
				public boolean onLongClick(View paramView) {
					System.out.println(temp);
					longpress = true;
					AppParameters.people = AppParameters.listPeople.get(temp);
					final Dialog dialog = new DialogActionThread(context).getInstance();
					LinearLayout addview_contact = (LinearLayout) dialog.findViewById(R.id.btn_addview_contact);
					addview_contact.setOnClickListener(new OnClickListener() { 
						@Override
						public void onClick(View v) {
							dialog.dismiss();
							// TODO Auto-generated method stub
							contactID = smsUtils.getContactIDByNameAndPhoneNumber(
									AppParameters.people.displayName,
									AppParameters.people.phoneNumber);
								
							if(contactID == -1){
								Intent intent = new Intent(Intent.ACTION_INSERT);
								intent.setType(ContactsContract.Contacts.CONTENT_TYPE);

								intent.putExtra(ContactsContract.Intents.Insert.PHONE, AppParameters.people.phoneNumber);

								startActivityForResult(intent, INSERT_CONTACT);
								
							}else{
								String str_contactID = String.valueOf(contactID).trim();
								Intent intent = new Intent(Intent.ACTION_VIEW);
								Uri myPhoneUri = Uri.withAppendedPath(
										ContactsContract.Contacts.CONTENT_URI, str_contactID);
								intent.setData(myPhoneUri);
								startActivityForResult(intent, VIEW_CONTACT);
							}
						}
					});
					
					return false;
				}
			});
			
			
			return convertView;

		}
	}

	private class ViewHolder {
		TextView tv;
		ImageView icon;
		ImageView status;
		TextView recentMes;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		reSetupActivity();
	}
	
	private void reSetupActivity(){
		if(adapter!=null){
			adapter.notifyDataSetChanged();
		}
	}
	
	private String getRecentMessage(String message){
		if(message.length() > 30){
			return message.substring(0,29)+ "...";
		}
		return message;
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		System.out.println("activity result");
		if(requestCode == INSERT_CONTACT){
			if(resultCode == Activity.RESULT_OK){
				Uri newUri = data.getData();
				if(newUri == null){
					return;
				}
				Cursor cursor = getContentResolver().query(newUri, null, null, null, null);
				if(!cursor.moveToFirst()){
					return;
				}
				String displayName = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
				AppParameters.people.displayName = displayName;
				smsUtils.updatePeople(AppParameters.people);
				adapter.notifyDataSetChanged();
			}
			
		}
		if(requestCode == VIEW_CONTACT){
			if(contactID != -1){
				String displayName = smsUtils.getDisplayNameByContactID(contactID);
				if(displayName == null){
					displayName = AppParameters.people.phoneNumber;
				}
				AppParameters.people.displayName = displayName;
				smsUtils.updatePeople(AppParameters.people);
				adapter.notifyDataSetChanged();
			}
		}
	}
	

	/**
     * Snarf the menu key.
     */
	public boolean onKeyDown(int keyCode, KeyEvent event) { 
	    if (keyCode == KeyEvent.KEYCODE_MENU) {
	    	doMenu();
	    	return true; //always eat it!
	    }
		return super.onKeyDown(keyCode, event); 
	} 

	/**
     * Load up our menu.
     */
	private void loadMenuItems() {
		//This is kind of a tedious way to load up the menu items.
		//Am sure there is room for improvement.
		ArrayList<CustomMenuItem> menuItems = new ArrayList<CustomMenuItem>();
		CustomMenuItem cmi = new CustomMenuItem();
		cmi.setCaption(getString(R.string.menu_send_message));
		cmi.setImageResourceId(R.drawable.icon1);
		cmi.setId(MENU_ITEM_1);
		menuItems.add(cmi);
		cmi = new CustomMenuItem();
		cmi.setCaption("Second");
		cmi.setImageResourceId(R.drawable.icon2);
		cmi.setId(MENU_ITEM_2);
		menuItems.add(cmi);
		cmi = new CustomMenuItem();
		cmi.setCaption(getString(R.string.menu_search));
		cmi.setImageResourceId(R.drawable.icon4);
		cmi.setId(MENU_ITEM_3);
		menuItems.add(cmi);
		cmi = new CustomMenuItem();
		cmi.setCaption(getString(R.string.menu_setting));
		cmi.setImageResourceId(R.drawable.icon3);
		cmi.setId(MENU_ITEM_4);
		menuItems.add(cmi);
		if (!mMenu.isShowing())
		try {
			mMenu.setMenuItems(menuItems);
		} catch (Exception e) {
			AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setTitle("Egads!");
			alert.setMessage(e.getMessage());
			alert.show();
		}
	}
	
	/**
     * Toggle our menu on user pressing the menu key.
     */
	private void doMenu() {
		if (mMenu.isShowing()) {
			mMenu.hide();
		} else {
			//Note it doesn't matter what widget you send the menu as long as it gets view.
			mMenu.show(findViewById(R.id.lv_activity_main));
		}
	}

	/**
     * For the demo just toast the item selected.
     */
	@Override
	public void MenuItemSelectedEvent(CustomMenuItem selection) {
		
		switch(selection.getId()){
			case 1:
				Intent intent = new Intent(MainActivity.this,ComposeSMSActivity.class);
				startActivity(intent);
				break;
			case 2:
				break;
			case 3:
				break;
			case 4:
				break;
			default:
				break;
		}
	}
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		//super.onBackPressed();
		if(mMenu.isShowing()){
			mMenu.hide();
		}
		else{
			finish();
		}
	}
	
	private class LoadViewTask extends AsyncTask<Void, Integer, Void> {
		Dialog dialog;
		int statusAccess;
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			
			statusAccess = smsUtils.getStatusAccess();
			if(statusAccess == 0){
				dialog = new DialogWait1Time(context).getInstance();
			}
		}
		
		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			if(statusAccess ==0){
				configApplication();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if(statusAccess == 0){
				dialog.dismiss();
			}
			setContentView(R.layout.activity_main1);
			setupComponents();
			loadView();
		}
	}
	
}
